<?php

namespace App\Http\Controllers\Api;

use App\Exceptions\UserException;
use App\Http\Helper\BusinessHelper;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Http\Response;
use App\Services\IdEncryptService;
use App\Services\WxComponentHelper;
use CategoryRepository;
use TestingConfig;
use ParamConfig;
use TestingDetailService;
use UserRecordService;
use ResultTypeService;
use ResultAttributeService;
use TestingItemService;
use TestingDeveloperService;
use DeveloperLinkService;
use App\Models\LogHelper;
use TestingAlgoHelper;
use App\Services\AESHelper;
use TestingVisitService;
use WechatUserService;
class ApiController extends Controller
{
    const ENCODE_KEY = 'qiezi';

    public function cateList(){
        $dev_code = TestingConfig::getValue('testing.display_dev_code');
        $list = CategoryRepository::getList($dev_code);
        LogHelper::log('testing');
        return apiSuccess($list);
    }

    /**返回测评列
     * @return array
     */
    public function testingList(){
        $dev_code = TestingConfig::getValue('testing.display_dev_code');
        $dataCode = array('union_code'=>$dev_code,'enable'=>1);
        $unionCode = TestingDeveloperService::checkUnionCode($dataCode);
        $list = TestingDetailService::getList($unionCode['union_code']);
        $data['list'] = [];
        if($list){
            foreach ($list as $key => &$val){
                //加密id
                $id = IdEncryptService::encryption($val->id,'encode');
                $val['tid'] = $id;
                $val['icon']= TestingConfig::getValue('website_url').'/upload/'.$val['icon'];
                unset($val['id']);
                array_push($data['list'],$val);
            }
        }else{
            return apiError();
        }
        return apiSuccess($data);
    }


    /**控制跳转
     * @param $id
     * @param $type
     * @return array
     */
    public function TestingDetail(Request $request,$type,$id,$uid){

        if($id && $uid && $type){
            //获取appid
            $appid = empty($request->input('appid'))?"":$request->input('appid');
            $thirdPartyName = $request->input('thirdpartyName') ? mb_strtolower($request->input('thirdpartyName')) : '';
//            LogHelper::log('$thirdPartyName===========>'.$thirdPartyName);
            //获取tid,解密
            $detail_id = IdEncryptService::encryption($id,'decode');
            $tid = $detail_id[0];
            //增加测评的名称
            if(!$detail = TestingDetailService::getById($tid)){
                return apiErrcode('tid_invalid');
            }
            //处理第三方uid对应的逻辑。判断uid是否为第三方的uid还是为我们帐号中心的uid
            if($decodeData = IdEncryptService::encryption($uid,'decode')){
                $uid = $decodeData[0];
            }
            //$uid = TestingDetailService::handleThirdpartyUid($detail['dev_union_code'],$uid);
            //校验是否已经答过
            $cacheKey = getCacheKey('testing.cache_key.user_recode.record').$tid."_".$uid;
            $result = UserRecordService::getByUid($uid,$tid);
            if($type=='retry' && $result){//显示题
                UserRecordService::forget($cacheKey);
                $type = 'detail';
                $this -> visitRedis($uid,$tid,$type);
                $data = $this -> testingItem($tid);
            }elseif(is_null($result)){//显示题
                $type = 'detail';
                $this -> visitRedis($uid,$tid,$type);
                $data = $this -> testingItem($tid);
            }else {//显示结果
                $type = 'result';
                $this -> visitRedis($uid,$tid,$type);
                $data = $this->testingResult($uid, $tid,$appid,$thirdPartyName);

            }
            $data['name'] = $detail['name'];
            $userLog = [
                'uid' => $uid,
                'tid' => $tid,
                'encode_tid' => $id,
                'testing_name' => $detail['name'],
            ];
            $this->log($userLog,'user_access_testing_log');
            return apiSuccess($data);
        }else{
            return apiError();
        }

    }


    /**根据用户uid和测评的id返回测评结果接口
     * @param $uid
     * @param $detail_id
     * @return array
     */
    public function testingResult($uid, $detail_id,$appid,$thirdPartyName = ''){
        $data = [];
        $result = UserRecordService::getByUid($uid,$detail_id);
        if($result){
            $data['score']=is_null($result['score'])?null:round($result['score'],2);
            $data['result']=$result['conclusion'];
//            $data['attrs']=$this->testingAttribute($uid,$detial_id,$result['score']);
            $result = ResultTypeService::chooseResult($uid,$detail_id);
            $data['attrs'] = $result['attrs'];
            $data['chatparam'] =$result['chatparam']=='zero'?'0':$result['chatparam'];
            $data['chatType'] = $result['chatType'];
            $data['link'] = DeveloperLinkService::getClientLinkByTid($detail_id,$thirdPartyName);
            $data['route']=false;
            //对接中英测评的用户系统
            $zygsUrl=ParamConfig::getValue('zygs_health_url');
            if($data['link'] && $data['link']['url']==$zygsUrl) {
                $data['link']['url']=$zygsUrl.'?user_id='.$uid;
            }
            //显示结果页按钮，中粮数字健康定制
            $show_button_appids = ParamConfig::getValue('WX.component.resultpage.show.button');
            $show_button_appids = json_decode($show_button_appids,true);
            if($appid && in_array(base64_decode($appid),$show_button_appids)){
                //post数据url
                //$key = base64_decode($appid)."_tplid";
                $tplid = ParamConfig::getValue("remind_tpl_id");
                $base = TestingConfig::getValue('website_url');
                $uid_encode = IdEncryptService::encryption($uid,'encode');
                $data['package'] = $base."/api/testing/wechat/sendtpl/".$uid_encode."/".$appid.'/'. $tplid;
            }
            return $data;
        }else{
            return apiError();
        }

    }

    /**返回测评建议
     * @param $tid
     * @param $score
     * @return array
     */
    public function testingAttribute($uid,$tid,$score){
        $detail = TestingDetailService::getById($tid);
        if($detail) {
            $result_type_id_arr = explode(',', $detail['result_type']);
            $result = ResultTypeService::getResult($uid,$result_type_id_arr, $score);
            return $result;
        }else{
            return apiError();
        }
    }

    /**返回测评title
     * @param $tid
     * @param $score
     * @return array
     */
    public function TestingAttributeTitle($tid,$score){
        $detail = TestingDetailService::getById($tid);
        //LogHelper::log('===============>'.__FUNCTION__);
        //LogHelper::log($tid.'====>'.$score);
        //LogHelper::log($detail);
        if($detail) {
            $result_type_id_arr = explode(',', $detail['result_type']);
            $result="";
            if(!is_null($score)){
                $result = ResultTypeService::getTitle( $result_type_id_arr, $score);
            }
            return $result;
        }else{
            return apiError();
        }
    }

    /**根据测评id返回题目列表
     * @param $detial_id
     * @return mixed
     */
    public function testingItem($detial_id){
        $result =  TestingDetailService::getItem($detial_id);
        if($result){
            $guide=TestingDetailService::getById($detial_id);
            //$result['guide']=['note'=>$guide['note'],'time'=>$guide['time'],'gist'=>$guide['gist']];
            $result['guide']=['note'=>$guide['note'],'time'=>$guide['time'],'gist'=>$guide['gist']];
            return $result;
        }else{
            return apiError();
        }

    }

    /**
     * 提交测试题目
     * @param Request $request
     * @return array
     * @throws UserException
     */
    public function submitTesting(Request $request){
        $uid = $request->input('uid');
        $tid = $request->input('tid');
        $answers = $request->input('answers');
        $testingTime = $request->input('testtime');
        $fromAppid = $request->input('appid');
        $thirdpartyName = $request->input('thirdpartyName');
        $nutritionist_id = $request->input('nutritionist_id');
        $order_id = $request->input('order_id');
        $scene = $request->input('scene');
        $flowTesting = $request->input('flowTesting');
        $free_order_id = $request->input('free_order_id');
        $nickName =  $request->input('nick_name');
        //免费营的自动创建订单的虚拟id
        $virtualOid = $request->input('virtual_oid');
        $tid = IdEncryptService::encryption($tid,'decode');
        $tid = $tid[0];
        if (!in_array($tid, BusinessHelper::canTestingTids())) {
            throw new UserException("你的操作不被允许");
        }
        if($uid && $tid && $answers){
            LogHelper::log('submitTesting=====');
            LogHelper::log('$thirdpartyName====='.$thirdpartyName);

            if(!$testingInfo = TestingDetailService::getById($tid)){
                return apiErrcode('tid_invalid');
            }
            //处理第三方uid对应的逻辑。判断uid是否为第三方的uid还是为我们帐号中心的uid
            if($decodeData = IdEncryptService::encryption($uid,'decode')){
                $uid = $decodeData[0];
            }
            //$uid = TestingDetailService::handleThirdpartyUid($testingInfo['dev_union_code'],$uid);
            $data['answers'] = $answers;
            $data['uid'] = $uid;
            if(!$nickName){
                $nickName = $thirdpartyName ? $uid : WechatUserService::getNickNameByUid($uid);
                if($scene == "wxa"){//来自小程序扫邀请码
                    $nickName = WechatUserService::getNickNameByUid($uid);
                }
            }else{
                $nickName = urldecode(base64_decode($nickName));
            }
            $data['nick_name']= $nickName;
            $data['testing_name']=TestingDetailService::getNameByTid($tid);
            $data['tid'] = $tid;
            if($fromAppid){//区分公众号
                $data['from_appid'] = base64_decode($fromAppid);
            }
            LogHelper::log("thirdpartyName===================>".$thirdpartyName);
            if($thirdpartyName){
                $data['from_partner'] = $thirdpartyName;
                $developer = TestingDeveloperService::getByAbbreviation($thirdpartyName);
                $appid = $developer['appid'];
                //判断是否为减脂openapi的合作伙伴，从而确定订单编号和营养师编号
                $jzOpenApiPartners = json_decode(TestingConfig::getValue('jz.openapi.partners'),true);
                LogHelper::log("jzOpenApiPartners========>".json_encode($jzOpenApiPartners));
                LogHelper::log("appid==============>".$appid);
                if(in_array($appid,$jzOpenApiPartners)){
                    $orderData = UserRecordService::syncJzOpenApiOrderInfo($appid,$uid,$tid);
                    LogHelper::log("orderData==============>".json_encode($orderData));
                    $data['nutritionist_id'] = $orderData['nutritionist_id'];
                    $data['order_id'] = $orderData['order_id'];
                }
            }
            if($free_order_id){
                $data['free_order_id']= $free_order_id;
            }
            if($nutritionist_id){
                $data['nutritionist_id']= $nutritionist_id;
            }
            if($order_id){
                $data['order_id'] = $order_id;
            }
            if($virtualOid){
                $data['virtual_oid'] = $virtualOid;
            }
            $typeFourExpress = TestingItemService::typeFourItem($data['tid']);
            $typeFourExpress = empty($typeFourExpress) ? null : $typeFourExpress;
            $reslut = TestingAlgoHelper::calculate($data['tid'],$data['answers'],$typeFourExpress);
            $data['score']=$reslut['totalScore'];
            $data['final_answers']=$reslut['finalAnswerStr'];
            $title = $this -> TestingAttributeTitle($data['tid'],$data['score']);
            $data['conclusion'] = TestingAlgoHelper::getConclusion($data['tid'],$data['score'],$data['answers'],$title,$typeFourExpress);
            $data['testtime'] = (int)$testingTime;
            LogHelper::log($data);
            $reslut = UserRecordService::stroeResult($data);
            if($reslut){
                $update = TestingDetailService::updataTestTimes($data['tid']);
                //调用减脂后台引流工具
                if($flowTesting){
                    UserRecordService::flowRecordPost($reslut);
                }
                //代谢用户
                if($free_order_id){
                    UserRecordService::freeOrderPost($reslut);
                }

                if($virtualOid){
                    UserRecordService::syncVirtualOrderRecord($reslut);
                }

                if($update){
                    return apiSuccess();
                }else{
                    return apiError();
                }
            }else{
                return apiError();
            }
        }else{
            return apiFailed();
        }
    }

    public function encodeUrl(Request $request){
        $url = $request->input('url');
        $urlArr = explode(',',$url);
        if(count($urlArr) <= 0){
            return apiFailed(null,'url不正确');
        }
        $urls = [];
        foreach ($urlArr as $u) {
            $urlEncode = base64_encode($u);
            array_push($urls,$urlEncode);
        }
        $data['url'] = implode(',',$urls);
        return apiSuccess($data);
    }

    /**接口访问统计
     * @param $uid
     * @param $tid
     * @param $type
     * @return mixed
     */
    protected function visitRedis($uid,$tid,$type){
        $listKey = getCacheKey('testing.cache_key.reids.visit');
        TestingVisitService::createRedisList($uid,$tid,$type,$listKey);
    }

    /**
     * 定时任务插入数据库
     */
    public function timingToMysql(){
        $listKey = getCacheKey('testing.cache_key.reids.visit');
        TestingVisitService::RedisSaveToMysql($listKey);
    }
}
